CODE 102. Next Permutation

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/01/2013-11-01-CODE 102 Next Permutation/

访问原文「CODE 102. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

``

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void nextPermutation(int[] num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
List<Integer> rest = new ArrayList<Integer>();
int i = 0;
for (i = num.length - 1; i >= 1; i--) {
if (num[i] <= num[i - 1]) {
rest.add(num[i]);
} else {
break;
}
}
if (i <= 0) {
Arrays.sort(num);
} else {
int j = 0;
rest.add(num[i]);
for (; j < rest.size(); j++) {
if (rest.get(j) > num[i - 1]) {
break;
}
}
int tmp = rest.get(j);
rest.set(j, num[i - 1]);
num[i - 1] = tmp;
for (j = 0; i < num.length; i++, j++) {
num[i] = rest.get(j);
}
}
}
Jerky Lu wechat
欢迎加入微信公众号